package com.redoor.app.stake.workflow.configurer;

import com.redoor.app.stake.auth.model.BaseUser;
import com.redoor.app.stake.auth.service.BaseUserService;
import com.redoor.app.stake.workflow.model.BaseWorkorder;
import com.redoor.app.stake.workflow.service.BaseWorkOrderRedisService;
import org.apache.tomcat.websocket.WsSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.*;
import org.springframework.web.socket.adapter.standard.StandardWebSocketSession;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by wangjunlei on 2018/4/2.
 */
public class WorkOrderWebSocketHandler implements WebSocketHandler {

    @Autowired
    private BaseUserService baseUserService;

    @Autowired
    private BaseWorkOrderRedisService baseWorkOrderRedisService;


    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        while (session.isOpen()){
            BaseUser baseUser = baseUserService.getShiroUser(((WsSession)((StandardWebSocketSession)session).getNativeSession()).getHttpSessionId());
            if(baseUser == null){
                return;
            }
            //todo 获取用户的组织机构信息并判断用户是否有审核工单的权限
            BaseWorkorder baseWorkorder = baseWorkOrderRedisService.getRemindWorkOrderFromRedis("1111");
            if(baseWorkorder != null){
                //todo 根据工单类型判断用户是否有该类型工单处理权限，有则推送到前端，每隔5分钟查询一次用户拥有的工单列表
                // 发送消息
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                session.sendMessage(new TextMessage(df.format(new Date())+":工单"+baseWorkorder.getUuid()));
                //messagingTemplate.convertAndSend("/websocket/topic/callback", df.format(new Date())+":工单"+baseWorkorder.getUuid());
            } else {
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                session.sendMessage(new TextMessage(df.format(new Date())));
            }
            Thread.sleep(1000);
        }
    }

    @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {

    }

    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
        if(webSocketSession.isOpen()){
            webSocketSession.close();
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {

    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
